﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Diagnostics;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private const string namechcol = "Флаг";      
        private SqlConnection conn;
        private DataTable dt_rep;
        private delegate void Deleg();
        private Deleg del;
        private DataTable dt_pharm = new DataTable();                   //- Для вывода списка аптек
        private DataTable dt_action = new DataTable();
        private DataTable ph_par = new DataTable();
        private DataTable act_par = new DataTable();
        private string storproc = "";
        private SqlStorProc.sp_params[] sp_par = new SqlStorProc.sp_params[2];
        
        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True");

            comboBox1.Items.Add(new NewItem() { ParamID = null, ParamComment = "Все" });
            comboBox1.SelectedIndex = 0;

            foreach (DataRow row in new SqlStorProc().SqlProcExecWithQueryOneTable(conn, "pas_Actions_UserCreate", 300, new SqlStorProc.sp_params[0]).Rows)
                comboBox1.Items.Add(new NewItem() { ParamID = row[0], ParamComment = row[1].ToString() });
        }

        private void StartCreateRep(object sender, EventArgs e)
        {
            sp_par[0].name = "@actstatus";
            if (radioButton1.Checked) sp_par[0].value = 0;
            if (radioButton2.Checked) sp_par[0].value = 1;
            if (radioButton3.Checked) sp_par[0].value = 2;
            if (radioButton4.Checked) sp_par[0].value = 3;
            sp_par[1].name = "@creator";
            sp_par[1].value = (comboBox1.SelectedItem as NewItem).ParamID;
            storproc = "pas_Actions_Rep_ActionParams";

            del = new Deleg(CreateRep);
            this.Text += " Формируется";
            IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); //
            panel1.Enabled = false;
            dataGridView1.Enabled = false;
        }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            if (dt_rep.Rows.Count > 0)
            {
                dataGridView1.Invoke((Func<object>)(() => dataGridView1.DataSource = dt_rep.DefaultView));
            }
        }

        private void CreateRep()
        {
            if (conn.State == ConnectionState.Closed) conn.Open();
            try
            {
                dt_rep = (new SqlStorProc()).SqlProcExecWithQueryOneTable(conn, storproc, 3000, sp_par);
                //dataGridView1.DataSource = dt_rep.DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                conn.Close();
            }

        }

        private SqlDataReader RepProc(SqlConnection sqlcon)//метод для вызова хранимки
        {
            SqlCommand sqlcom = sqlcon.CreateCommand();
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.CommandText = @"sp_name"; //имя хранимой процедуры
            sqlcom.CommandTimeout = 300;

            return sqlcom.ExecuteReader();
        }

        private DataTable DownloadData(SqlConnection con, string proc)
        {
            SqlCommand pharm = con.CreateCommand();
            pharm.CommandText = proc;
            pharm.CommandType = CommandType.StoredProcedure;
            DataTable dt = new DataTable();
            dt.Load(pharm.ExecuteReader());
            dt.Columns[0].ReadOnly = false;
            return dt;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //- Выгрузить в Excel
            if (dataGridView1.DataSource == null)
            {
                MessageBox.Show("Нет данных для выгрузки в Excel");
                return;
            }
            ExpToExcel ex = new ExpToExcel();
            ex.ExportToExcel(dataGridView1);
        }

    }
}
